from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import datetime
import os
import time as _time


# 如果没找到 而且存在分页 那么就下一页继续查找
def loop(name, time):
    isFound = False
    try:
        table_div = WebDriverWait(DRIVER, 3).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "table.m-table")))

        username_as = table_div.find_elements_by_css_selector("a.txt")
        for username_a in username_as:
            if username_a.text.lower() == name.lower():
                isFound = True
                username_a.click()
                return spider(time)

        if isFound == False:
            next_btn = DRIVER.find_element_by_css_selector(".zbtn.znxt")
            is_disabled = "js-disabled" in next_btn.get_attribute("class")
            if is_disabled == False:
                next_btn.send_keys(Keys.ENTER)
                loop(name, time)
            else:
                print("没有查询到该用户！")
                DRIVER.close()
                return ""

    except Exception as ex:
        print(ex)
        DRIVER.close()
        return ""


# 查找用户 跳转其主页 并开始爬取
def moveToHomepageAndSpider(name, time):
    search_url = "http://music.163.com/#/search/m/?type=1002&s=" + name
    DRIVER.get(search_url)
    DRIVER.switch_to_frame("g_iframe")
    output = loop(name, time)
    return output


# 爬取歌单信息
def spider(time):
    output = """DATE: {0}\n""".format(time)

    all_listened_tag = DRIVER.find_element_by_id(
        'rHeader').find_element_by_tag_name('h4')
    all_listened_count = all_listened_tag.text
    output = output + "听歌排行: {0}\n".format(all_listened_count)

    msks = DRIVER.find_element_by_id("cBox").find_elements_by_css_selector(
        ".msk")

    # 不知道为什么只要一个歌单的时候 click失效 所以提出来 并用js脚本执行
    if len(msks) == 1:
        js = "document.getElementsByClassName('msk')[0].click()"
        DRIVER.execute_script(js)
        _time.sleep(1)
        playlist_track_count = DRIVER.find_element_by_id(
            "playlist-track-count").text
        play_count = DRIVER.find_element_by_id("play-count").text
        collection_name = DRIVER.title.split(' - ')[0]
        output = output + "   {0}: {1}首歌 | 播放{2}次\n".format(
            collection_name, playlist_track_count, play_count)
        print(output)
    else:
        for i in range(0, len(msks)):
            collection = DRIVER.find_element_by_id(
                "cBox").find_elements_by_css_selector(".msk")[i]
            # 不知道为什么只有一个歌单的时候 click无效！
            collection.click()
            playlist_track_count = DRIVER.find_element_by_id(
                "playlist-track-count").text
            play_count = DRIVER.find_element_by_id("play-count").text
            collection_name = DRIVER.title.split(' - ')[0]
            output = output + "   {0}: {1}首歌 | 播放{2}次\n".format(
                collection_name, playlist_track_count, play_count)
            print(output)
            DRIVER.back()

    output = output + "End: {0}\n\n".format(time)
    DRIVER.close()
    return output


# 删除今天抓下来的数据段
def removeTodayInFile(time, fileName):
    if os.path.exists(fileName) == False:
        return
    file_o = open(fileName, 'rb+')
    line = file_o.readline()
    while line:
        bytes_ = str.encode(time)
        if (bytes_ in line):
            # 似乎pytho3中要使用非0为偏移量 需要open mode=b
            # 虽然oepn mode=b但是偏移量仍是以字符串长度计算
            file_o.seek(0 - len(bytes.decode(line)), 1)
            file_o.truncate()
            break
        line = file_o.readline()


# 把结果增加到文件里
def appendToFile(content, fileName):
    file_o = open(fileName, 'a')
    file_o.write(content)
    file_o.close()


#
print("🌻 请输入你的网易云音乐昵称:")
username = "lena9424"
temp = input()
if temp:
    username = temp

options = webdriver.FirefoxOptions()
options.add_argument('headless')
DRIVER = webdriver.Firefox(firefox_options=options)

today = datetime.date.today().strftime("%Y-%m-%d")
output = moveToHomepageAndSpider(username, today)

if output != "":
    print(output)
    file_name = "outputs/" + username + ".txt"
    removeTodayInFile(today, file_name)
    appendToFile(output, file_name)
